package com.zero.service.impl;

import com.zero.service.WeatherService;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@CacheConfig(cacheNames = "com.zero") // 配置缓存名称的前缀
public class WeatherServiceImpl implements WeatherService {

    private static final Logger logger = LoggerFactory.getLogger(WeatherServiceImpl.class);

    @Override
    @Cacheable(key = "'weather_' + #city")
    public String getWeatherByCity(String city) {
        return getWeatherByOkHttpClient(city);
    }

    // 更新缓存，这里直接将weather参数返回，然后@CachePut会将weather更新到对应的key中
    @Override
    @CachePut(key = "'weather_' + #city")
    public String manuallyUpdateWeatherCacheByCity(String city, String weather) {
        logger.info("manuallyUpdateWeatherCacheByCity successfully, city={}, weather={}", city, weather);
        return weather;
    }

    // 删除缓存(cacheNames等效于key)
    @Override
    @CacheEvict(key = "'weather_' + #city")
    public String manuallyDeleteWeatherCacheByCity(String city) {
        logger.info("manuallyDeleteWeatherCacheByCity successfully, city={}", city);
        return "delete cache successfully";
    }

    @Override
    public String getWeatherWithoutCacheByCity(String city) {
        return getWeatherByOkHttpClient(city);
    }

    @NotNull
    private String getWeatherByOkHttpClient(String city) {
        logger.info("getWeatherByCity without cache, city={}", city);
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(new Request
            .Builder()
            .url("http://wthrcdn.etouch.cn/weather_mini?city=" + city)
            .build());
        String result;
        try {
            result = call.execute().body().string();
        } catch (IOException e) {
            logger.error("There is an error when get weather by city={}", city);
            return "get weather failed";
        }
        return result;
    }
}
